<template>
  <view class="dl-select" hover-class="none" hover-stop-propagation="false">
    <view class="dl-position-rel" :style="{ height: '100%', 'z-index': showMenu ? 3 : 1 }">
      <view class="dl-select-btn" hover-class="none" hover-stop-propagation="false">
        <u-button
          :icon="showMenu ? 'arrow-up' : 'arrow-down'"
          plain
          :type="showMenu ? 'primary' : 'info'"
          :text="showItemStr"
          iconColor="#4E5969"
          :custom-style="customStyle1"
          :hairline="false"
          @click="showMenu = !showMenu"
        ></u-button>
      </view>
      <view class="dl-select-menu dl-position-abs" :style="{ display: showMenu ? 'block' : 'none' }">
        <u-button v-for="(option, index) in options" :key="index" :text="option.name" :custom-style="customStyle2" :hairline="false" @click="handleOptionClick(option)"> </u-button>
      </view>
    </view>
    <u-overlay :show="showMenu" zIndex="2" @click="showMenu = false" opacity="0.4"> </u-overlay>
  </view>
</template>

<script>
export default {
  name: 'DlSelect',
  props: {
    value: {
      type: [Number, String],
      default: null
    },
    options: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    value: {
      immediate: true,
      handler: function (newVal, oldVal) {
        const currentOption = this.options.find(item => item.id === newVal)
        currentOption && (this.showItemStr = currentOption.name)
      }
    }
  },
  data() {
    return {
      showMenu: false,
      showItemStr: '',
      customStyle1: Object.freeze({
        flexFlow: 'row-reverse',
        borderRadius: 0,
        borderWidth: 0,
        columnGap: '40rpx',
        justifyContent: 'space-between',
        height: '100%'
      }),
      customStyle2: Object.freeze({
        borderRadius: 0,
        borderWidth: 0,
        justifyContent: 'flex-start'
      })
    }
  },
  methods: {
    handleOptionClick(option) {
      if (option.id == this.value) {
        this.showMenu = false
      } else {
        this.$emit('input', option.id)
        this.$emit('change', option)
        this.showMenu = false
      }
    }
  }
}
</script>

<style lang="scss">
.dl-select {
  height: 100%;
  &-btn {
    height: 100%;
    button {
      text {
        font-size: 30rpx !important;
      }
    }
  }
  &-menu {
    width: 100%;
    background: #ffffff;
    box-shadow: 0rpx 4rpx 10rpx 0rpx rgba(0, 0, 0, 0.302);
    border-radius: 5rpx;

    button {
      text {
        font-size: 30rpx !important;
        color: #000000;
      }
    }
  }
}
</style>
